package com.xxtx.trade.thread;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xxtx.trade.agent.mapper.TradeSysAgentMapper;
import com.xxtx.trade.common.util.cache.CacheManager;
import com.xxtx.trade.common.util.model.Result;
import com.xxtx.trade.fieldManage.mapper.FieldManageMapper;
import com.xxtx.trade.sysUser.dto.*;
import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Configuration
@Service
@Slf4j
public class HandleAllDataAsync {

    private static final Logger LOGGER = LoggerFactory.getLogger(HandleAllDataAsync.class);

    // 使用异步的方式将 Redis 中的数据插入数据库
    @Autowired
    TradeSysAgentMapper tradeSysAgentMapper;


    @Autowired
    private FieldManageMapper fieldManageMapper;

    @Value("${default.tiktokCache}")
    private String tiktok_cache;

    @Value("${default.tencentCache}")
    private String tencent_cache;

    @Value("${default.baiduCache}")
    private String baidu_cache;

    @Autowired
    private CacheManager cacheManager;

    @Async
    public void asyncDataInsert(String key, int total) {
        // key：处理的数据类型，腾讯、抖音区分
        // count：每次处理的数据量

        //一次性查询全部urlNote，用以配置agentName等
        List<Map<String, Object>> urlNotes = tradeSysAgentMapper.selectAllUrlNote();
//        LOGGER.info(urlNotes.toString());
        List<String> urlNoteIndex = new ArrayList<>();
        for (Map<String, Object> map : urlNotes) {
            urlNoteIndex.add((String) map.get("urlNote"));
        }
        List<tiktokInfoDto> handle_list = new ArrayList<>();
        for (int i = 0; i < total; i++) {
            tiktokInfoDto dto = (tiktokInfoDto) cacheManager.lRPop(key);
            if (dto == null) break;
            String urlName = dto.getMyName();
            int index = urlNoteIndex.indexOf(urlName);
            dto.setUrlId((String) urlNotes.get(index).get("id"));
            dto.setUrlName((String) urlNotes.get(index).get("urlNote"));
            dto.setAgentId((String) urlNotes.get(index).get("agentId"));
            dto.setAgentName((String) urlNotes.get(index).get("agentName"));
            tradeSysAgentMapper.updateAddOneByUrlId(dto.getUrlId()); // 添加点击量
            handle_list.add(dto);
        }
        if (handle_list.size() != 0) {
//                LOGGER.info("-------------有数据插入---------------");
            tradeSysAgentMapper.batchInsertDouYinData(handle_list);
        }
        urlNotes.clear();
        urlNoteIndex.clear();
        handle_list.clear();// 清理引用
    }

    @Async
    public void asyncTencentDataInsert(String key, int total) {
        //一次性查询全部urlNote，用以配置agentName等
        List<Map<String, Object>> urlNotes = tradeSysAgentMapper.selectAllUrlNote();
//        LOGGER.info(urlNotes.toString());
        List<String> urlNoteIndex = new ArrayList<>();
        for (Map<String, Object> map : urlNotes) {
            urlNoteIndex.add((String) map.get("urlNote"));
        }
        List<TencentInfoDto> handle_list = new ArrayList<>();
        for (int i = 0; i < total; i++) {
            TencentInfoDto dto = (TencentInfoDto) cacheManager.lRPop(key);
            if (dto == null) break;
            String urlName = dto.getUrlName(); // 注意这里直接用了urlName，和抖音链接不太一样
            int index = urlNoteIndex.indexOf(urlName);
            dto.setUrlId((String) urlNotes.get(index).get("id"));
            dto.setUrlName((String) urlNotes.get(index).get("urlNote"));
            dto.setAgentId((String) urlNotes.get(index).get("agentId"));
            dto.setAgentName((String) urlNotes.get(index).get("agentName"));
            tradeSysAgentMapper.updateAddOneByUrlId(dto.getUrlId()); // 添加点击量
            handle_list.add(dto);
        }
        if (handle_list.size() != 0) {
            tradeSysAgentMapper.batchInsertTencentData(handle_list);
        }
        urlNotes.clear();
        urlNoteIndex.clear();
        handle_list.clear();
    }


    @Async
    public void asyncBaiduDataInsert(String key, int total) {
        // 异步插入百度的数据
        List<BaiDuInfoDto> handle_list = new ArrayList<>();
        //一次性查询全部urlNote，用以配置agentName等
        List<Map<String, Object>> urlNotes = tradeSysAgentMapper.selectAllUrlNote();
//        LOGGER.info(urlNotes.toString());
        List<String> urlNoteIndex = new ArrayList<>();
        for (Map<String, Object> map : urlNotes) {
            urlNoteIndex.add((String) map.get("urlNote"));
        }
        for (int i = 0; i < total; i++) {
            BaiDuInfoDto dto = (BaiDuInfoDto) cacheManager.lRPop(key);
            if (dto == null) break;
            String urlName = dto.getUrlName();
            int index = urlNoteIndex.indexOf(urlName);
            dto.setUrlId((String) urlNotes.get(index).get("id"));
            dto.setUrlName((String) urlNotes.get(index).get("urlNote"));
            dto.setAgentId((String) urlNotes.get(index).get("agentId"));
            dto.setAgentName((String) urlNotes.get(index).get("agentName"));
            tradeSysAgentMapper.updateAddOneByUrlId(dto.getUrlId()); // 添加点击量
            handle_list.add(dto);
        }
        if (handle_list.size() != 0) {
            tradeSysAgentMapper.batchInsertBaiDuData(handle_list);
        }
        handle_list.clear();
    }

    @Async
    public void asyncKuaiShouDataInsert(String key, int total){
        // 异步插入快手数据
        List<KuaiShouInfoDto> handle_list = new ArrayList<>();
        // 一次性查询全部urlNote，用以配置 agentName等
        List<Map<String, Object>> urlNotes = tradeSysAgentMapper.selectAllUrlNote();

        List<String> urlNoteIndex = new ArrayList<>();
        for (Map<String, Object> map :urlNotes){
            urlNoteIndex.add((String) map.get("urlNote"));
        }
        for (int i = 0; i < total; i++){
            KuaiShouInfoDto dto = (KuaiShouInfoDto) cacheManager.lRPop(key);
            if (dto == null) break;
            String urlName = dto.getUrlName();
            int index = urlNoteIndex.indexOf(urlName);
            dto.setUrlId((String) urlNotes.get(index).get("id"));
            dto.setUrlName((String) urlNotes.get(index).get("urlNote"));
            dto.setAgentId((String) urlNotes.get(index).get("agentId"));
            dto.setAgentName((String) urlNotes.get(index).get("agentName"));
            tradeSysAgentMapper.updateAddOneByUrlId(dto.getUrlId()); // 添加点击量
            handle_list.add(dto);
        }
        if (handle_list.size() != 0){
            tradeSysAgentMapper.batchInsertKuaiShouData(handle_list);
        }
        handle_list.clear();
    }

    @Async
    public Result asyncPhoneOwnershipInsert(PhoneOwnershipDto dto) {
        fieldManageMapper.insertPhoneOwnership(dto);
        return Result.success();
    }


}
